package com.example.bookexchange;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class AddressAdapter extends RecyclerView.Adapter<AddressAdapter.AddressViewHolder> {

    private final List<Address> addressList;
    private final OnAddressClickListener onAddressClickListener;

    // 构造函数，传入地址列表和点击事件的监听器
    public AddressAdapter(List<Address> addressList, OnAddressClickListener listener) {
        this.addressList = addressList;
        this.onAddressClickListener = listener;
    }

    @NonNull
    @Override
    public AddressViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_address, parent, false);
        return new AddressViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AddressViewHolder holder, int position) {
        Address address = addressList.get(position);

        holder.tvContactName.setText(address.getContactName());
        holder.tvPhoneNumber.setText(address.getPhoneNumber());
        holder.tvFullAddress.setText(address.getFullAddress());

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (onAddressClickListener != null) {
                onAddressClickListener.onAddressClick(address);
            }
        });
    }

    @Override
    public int getItemCount() {
        return addressList.size();
    }

    public static class AddressViewHolder extends RecyclerView.ViewHolder {
        TextView tvContactName, tvPhoneNumber, tvFullAddress;

        public AddressViewHolder(@NonNull View itemView) {
            super(itemView);
            tvContactName = itemView.findViewById(R.id.tvContactName);
            tvPhoneNumber = itemView.findViewById(R.id.tvPhoneNumber);
            tvFullAddress = itemView.findViewById(R.id.tvFullAddress);
        }
    }

    // 定义点击事件接口
    public interface OnAddressClickListener {
        void onAddressClick(Address address);
    }
}
